#include "goodspurchasingwindow.h"
#include "ui_goodspurchasingwindow.h"
#include<QFile>
#include<QJsonArray>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonValue>
#include<QDebug>
#include<QListWidgetItem>
#include"buyinform.h"
#include<QMessageBox>
#include "goodsoperatewindow.h"
#include"welcomewindow.h"
#include"managewindow.h"
#include<QDate>
#include<QTime>
#include<QCompleter>
//#define SERVER_IP "192.168.14.84"
#define PROT 6065
#define LOGPATH "./data/purchingLog.txt"
#define serverPath "./data/serverIP.txt"
goodsPurchasingWindow::goodsPurchasingWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::goodsPurchasingWindow)
{
    ui->setupUi(this);
    QList<QString> wordlist;
    wordlist<<"10000"<<"10001"<<"10002"<<"10003"<<"10004"<<"10005"<<"10006"<<"10007"<<"10008"<<"10009"<<"10010"
              <<"10011"<<"10012"<<"10013"<<"10014";
    QCompleter *completer=new QCompleter(wordlist,this);
    ui->lineEdit->setCompleter(completer);
    socket=new QTcpSocket;

    connect(socket,&QTcpSocket::connected,this,&goodsPurchasingWindow::connectedTohost);
    connect(socket,&QIODevice::readyRead,this,&goodsPurchasingWindow::readData);
    QFile *server=new QFile(serverPath);
   if(!server->open(QIODevice::ReadOnly))
   {
        qDebug()<<"open serverPath failed";
   }
  QByteArray arr=server->readAll();

    socket->connectToHost(QString(arr),PROT);

}

goodsPurchasingWindow::~goodsPurchasingWindow()
{
    delete ui;
}

void goodsPurchasingWindow::getValue( goods* good)
{
    goodslist<<good;
    totalprice+=(good->getBuyinNum()*good->getCostPrice());
   ui->countLabel->setNum(totalprice);
}

void goodsPurchasingWindow::on_SearchButton_clicked()
{

    QFile *goodsData=new QFile("./data/goods.json");
    if(!goodsData->open(QIODevice::ReadOnly))
    {
        qDebug()<<"open file failed ";
    }

   arr1=goodsData->readAll();


    goodsData->close();

    QJsonDocument doc=QJsonDocument::fromJson(arr1);

    QJsonObject object1= doc.object();

    QJsonValue value1=object1.value("Goods");
    qDebug()<< value1.toString();
    QJsonArray array1=  value1.toArray();



    bool goodsFound=false;

    QListWidgetItem *aitem1=new QListWidgetItem;
    aitem1->setSizeHint(QSize(431,125));

    for(int i=0;i<array1.size();i++)
    {
       if(ui->lineEdit->text()==array1.at(i).toObject().value("编号").toString())
       {
           goodsFound=true;
//           saledName<<array1.at(i).toObject().value("名字").toString();
           ui->goodsChooselistWidget->addItem(aitem1);
           buyinForm *Form1=new  buyinForm(array1.at(i).toObject().value("图片位置").toString(),
                                            array1.at(i).toObject().value("编号").toString(),
                                           array1.at(i).toObject().value("名字").toString(),
                                           array1.at(i).toObject().value("售卖单价").toDouble(),
                                           array1.at(i).toObject().value("库存").toInt(),
                                           array1.at(i).toObject().value("成本").toDouble(),
                                           this);
           Formlist<<Form1;

           ui->goodsChooselistWidget->setItemWidget(aitem1,Form1);
       }



    }

    if(!goodsFound)
    {
        QMessageBox::critical(this,"查找错误","无此货物，重新输入编号");
    }



}

void goodsPurchasingWindow::on_confirButton_clicked()
{
   for(int i=0;i<Formlist.size();i++)
   {
       //connect to each form;
       connect(this,&goodsPurchasingWindow::getgoods,Formlist[i],&buyinForm::sendGoods);
   }

       //emit to each form;
       emit getgoods();


}

void goodsPurchasingWindow::on_confirBuyButton_clicked()
{

    socket->write("getName#");
}

void goodsPurchasingWindow::on_returnButton_clicked()
{
    QObject* before=this->parentWidget();
    goodsOperateWindow *gp=dynamic_cast<goodsOperateWindow *>(before);
    gp->show();
    this->close();
}

void goodsPurchasingWindow::connectedTohost()
{
    qDebug()<<"已连接到服务器";
}

void goodsPurchasingWindow::readData()
{
    QByteArray data=socket->readAll();



    QFile *log=new QFile(LOGPATH);

   if(!log->open(QIODevice::WriteOnly|QIODevice::Append))
   {
       qDebug()<<"open log failed";
   }

   for(int j=0;j<goodslist.size();j++)
   {

    log->write("日期:"+QDate::currentDate().toString("yy-MM-dd").toUtf8()+"|"+" 时间:"+QTime::currentTime().toString().toUtf8()+"|货号:"+
              goodslist[j]->getnum().toUtf8()+"|货名:"+goodslist[j]->getName().toUtf8()+"|售价:"+QString::number(goodslist[j]->getSalePrice()).toUtf8()
               +"|进货价:"+QString::number(goodslist[j]->getCostPrice()).toUtf8()+"|买入数量:"+QString::number(goodslist[j]->getBuyinNum()).toUtf8()+"\r\n采购人:"+QString(data).toUtf8()+"\r\n");


    QFile *goodsData=new QFile("./data/goods.json");
    if(!goodsData->open(QIODevice::ReadOnly))
    {
        qDebug()<<"open file failed ";
    }
    qDebug()<<__LINE__<<__FUNCTION__;
    QByteArray arr1=goodsData->readAll();
    goodsData->close();

    QJsonDocument doc=QJsonDocument::fromJson(arr1);

    QJsonObject object1= doc.object();
    QJsonValue value1=object1.value("Goods");
    QJsonArray array1=  value1.toArray();



      for(int i=0;i<array1.size();i++)
        {

            if(goodslist[j]->getName().toUtf8()==array1.at(i).toObject().value("名字").toString())
            {

                qDebug()<<array1.at(i).toObject().value("售卖单价").toInt();

                QJsonObject tmp= array1.at(i).toObject();

                tmp.insert("编号",array1.at(i).toObject().value("编号").toString());
                tmp.insert("名字",array1.at(i).toObject().value("名字").toString());
                tmp.insert("成本",array1.at(i).toObject().value("成本").toDouble());
                tmp.insert("售卖单价",array1.at(i).toObject().value("售卖单价").toDouble());
                tmp.insert("卖出数量",array1.at(i).toObject().value("卖出数量").toInt());
                tmp.insert("库存",array1.at(i).toObject().value("库存").toInt()+goodslist[j]->getBuyinNum());
                tmp.insert("图片位置",array1.at(i).toObject().value("图片位置").toString());

                array1.removeAt(i);
                array1.insert(i,tmp);

                object1.insert("Goods",array1);



                qDebug()<<"名字"<<array1.at(i).toObject().value("名字").toString();
               qDebug()<<"卖出数量: "<<array1.at(i).toObject().value("卖出数量").toInt();
                qDebug()<<"库存: "<<array1.at(i).toObject().value("库存").toInt();

                break;

            }

        }


    doc.setObject(object1);
    QByteArray change=doc.toJson();


    if(!goodsData->open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        qDebug()<<"open file failed ";
    }

    goodsData->write(change);
    goodsData->close();



   }
    QMessageBox::information(this,"采购结果","采购成功");
    ui->goodsChooselistWidget->clear();
    ui->countLabel->clear();
    log->close();
}
